<template>
	<view class="page-delegate">
		<scroll-view scroll-y class="scroll-height">
			<view class="condition">
				<view class="contexts">
					<view class="conleft">事项标题</view>
					<view class="coninputright">{{formData.taskSubject}}</view>
				</view>
				<view class="conmenus">
					<view class="conleft">任务名称</view>
					<view class="conright">{{formData.taskName}}</view>
				</view>
				<view class="conmenus">
					<view class="conleft">更改类型</view>
					<view class="conright">{{formData.changeType | codeFormat(changeOptions)}}</view>
				</view>
				<view class="conmenus">
					<view class="conleft">状态</view>
					<view class="conright">{{formData.status | codeFormat(changeStatusOptions)}}</view>
				</view>
				<view class="conmenus">
					<view class="conleft">委托人</view>
					<view class="conright">{{formData.ownerName}}</view>
				</view>
				<view class="contexts">
					<view class="conleft">描述</view>
					<view class="coninputright">
						<textarea placeholder="请输入措施" auto-height v-model="formData.comment"/>
					</view>
				</view>
				<view class="contexts">
					<view class="user-select">
						<view class="conleft">任务变更候选人</view>
						<view class="conright">
							<button type="primary" size="mini" class="user-btn" @click="selectUser">添加</button>
							<button type="warn" size="mini" @click="delMultiple">删除</button>
						</view>
					</view>
					<view class="coninputright" v-if="showTable">
						<uni-table border stripe type="selection" @selection-change="change">
							<uni-tr>
								<uni-th align="center">候选人类型</uni-th>
								<uni-th align="center">执行人</uni-th>
								<uni-th align="center">管理</uni-th>
							</uni-tr>
							<uni-tr v-for="item in userList" :key="item.id">
								<uni-td align="center">{{ item.type == "employee" ? "用户" : "" }}</uni-td>
								<uni-td align="center">{{ item.name }}</uni-td>
								<uni-td align="center"><button type="warn" size="mini" @click="delSingle(item)">删除</button></uni-td>
							</uni-tr>
						</uni-table>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<view class="button-groups">
			<button type="primary" @click="delegate">转办</button>
		</view>
	</view>
</template>

<script>
	import { findByType, findByUserId, queryOrgManagerByOrgId } from '@/api/platform/common.js'
	import { getTaskChange, saveTaskChange } from '@/api/base/flow.js'
	import { updateDefectInfo, addChangeRecord } from '@/api/business/defect.js'
	import { addTaskTransfer } from '@/api/business/shiftduty.js'
	import { notice, utilities } from '@/utils/common.js'
	import constants from '@/utils/constants.js'
	
	export default {
		data() {
			return {
				type: '',
				bizKey: '',
				taskId: '',
				changeOptions: constants.flowChangeOptions,
				changeStatusOptions: constants.flowChangeStatusOptions,
				formData: {},
				userList: [],
				checkedUser: [],
				showTable: false
			}
		},
		onLoad(option) {
			this.type = option.type
			this.bizKey = option.bizKey
			this.taskId = option.taskId
			this.init()
		},
		methods: {
			async init() {
				await getTaskChange(this.taskId).then(res=>{
					this.formData = res.data
				})
				this.showTable = true
			},
			selectUser() {
				let that = this
				uni.navigateTo({
					url: '/pages/base/select-user-multi?type=delegate',
					events: {
						selectUserMulti(data) {
							data.forEach(item=>{
								if(JSON.stringify(that.userList).indexOf(JSON.stringify(item)) === -1) {
								    that.userList.push(item)
								}
							})
							that.reloadTable()
						}
					}
				})
			},
			change(e) {
				this.checkedUser = []
				if(e.detail.index.length > 0) {
					e.detail.index.forEach(index=>{
						this.checkedUser.push(this.userList[index])
					})
				}
			},
			delMultiple() {
				if(this.checkedUser.length === 0) {
					notice.toast("请选择记录!")
					return
				}
				this.checkedUser.forEach(user=>{
					this.delSingle(user)
				})
				
				this.reloadTable()
			},
			delSingle(item) {
				this.userList.forEach(function(value, index, arr){
					if(value.id === item.id) {
						arr.splice(index, 1)
					}
				})
				
				this.reloadTable()
			},
			reloadTable() {
				this.showTable = false
				this.$nextTick(()=>{
					this.showTable = true
				})
			},
			delegate() {
				if(this.userList.length === 0) {
					notice.toast("任务变更候选人数据不能为空，请选择！")
					return
				}
				
				const ownerIndex = this.userList.findIndex(item => item.id === this.formData.ownerId)
				if (ownerIndex > -1) {
					notice.toast('任务变更候选人不能包含委托人，请检查设置！')
					return
				}
				
				let changeList = []
				this.userList.forEach(user=>{
					changeList.push({
						executor: user.id,
						executorName: user.name,
						id: "",
						taskChangeId: "",
						type: "employee"
					})
				})
				this.formData.bpmTaskChangeAssignPoList = changeList
				const data = JSON.parse(JSON.stringify(this.formData))
				saveTaskChange(data).then(res=>{
					let changeRequest = {
						dfId       : this.bizKey,
						changeType : "zb", // 转办
						applyer    : uni.getStorageSync("userId"), // 申请人
						applyerName: uni.getStorageSync("userName"), // 申请人名称
						applyTime  : utilities.getNowDateTime(), // 申请时间
					}
					// 添加变更日志
					addChangeRecord(changeRequest)
					
					if(this.type == 'defect') {
						this.dealDefect()
					}
					if(this.type == 'shiftduty') {
						this.dealShiftduty()
					}
					
					notice.toast("保存流程任务变更成功")
					setTimeout(function(){
						utilities.backMore(0, 2)
					},2000)
				})
			},
			async dealDefect() {
				let levelID
				await findByType({ 'type': 'org' }).then((ret) => {
					if (ret.state === 200) {
						ret.data.forEach(item => {
							if (item.name === '班组') {
								levelID = item.id
							}
						})
					}
				})
				let mtnTeamNo
				let mtnTeamName
				let noticePersonId
				let noticePerson
				findByUserId({ 'userId': this.userList[0].id }).then(res => {
					res.data.forEach(item => {
						if (item.levelID === levelID) {
							mtnTeamNo = item.id
							mtnTeamName = item.name
							queryOrgManagerByOrgId({ 'OrgId': item.id }).then(ret => {
								if (ret.state === 200 && ret.data.dataResult[0]) {
									noticePersonId = ret.data.dataResult[0].id
									noticePerson = ret.data.dataResult[0].name
								}
							})
							return
						}
					})
				})
				
				let params = {
					dfId: this.bizKey,
					mtnPerson: this.userList[0].name,
					mtnPersonId: this.userList[0].id,
					noticepersonId: noticePersonId,
					noticeperson: noticePerson,
					mtnTeamNo: mtnTeamNo,
					mtnTeamName: mtnTeamName,
				}
				updateDefectInfo(params)
			},
			dealShiftduty() {
				let changeRequest = {
					taskId: this.bizKey, // 任务id
					transferId: uni.getStorageSync("userId"), // 转办人
					transferTime: utilities.getNowDateTime() // 转办时间
				}
				
				// 添加变更日志
				addTaskTransfer(changeRequest)
			}
		}
	}
</script>

<style lang="scss">
	@import '@/static/style/common-detail.scss';
	
	.page-delegate {
		overflow-y: auto;
		background-color: #f1f1f1;
	}
	
	.scroll-height {
		/* #ifdef APP-PLUS */
		height: calc(100vh - 56px);
		/* #endif*/
		/* #ifdef H5 */
		height: calc(100vh - 100px);
		/* #endif*/
	}
	
	.contexts:last-child {
		border-bottom: 0;
	}
	
	.user-select {
		display: flex; 
	}
	
	.user-btn {
		margin: 0 10px;
	}
</style>
